const { verify } = require('jsonwebtoken');
module.exports = (options) => {
  return async (ctx, next) => {
    const { app } = ctx
    let token = ctx.get('Authentication').split(' ')[1];
    let con = verify(token, app.config.jwtSecret, (err, decoded) => {
      if (err) {
        if (err.name == 'TokenExpiredError') {
          return {
            iat: 1,
            exp: 0,
            code: 401,
            msg: '令牌过期',
          };
        } else if (err.name == 'JsonWebTokenError') {
          return {
            iat: 1,
            exp: 0,
            code: 403,
            msg: '令牌无效',
          };
        }
      } else {
        return decoded;
      }
    });
    if (con.iat < con.exp) {
      await next();
      return true;
    } else {
      ctx.status = con.code;
      ctx.body = { message: con.msg };
      return false;
    }
  };
};
